package com.harassment.interception.interception.telephone;

import android.annotation.SuppressLint;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;

import io.reactivex.Completable;
import io.reactivex.CompletableEmitter;
import io.reactivex.CompletableOnSubscribe;
import io.reactivex.schedulers.Schedulers;

public class TelephoneStateListener{
    private static final String TAG = "TelephoneStateListener";
    private TelephoneRecord mTelephoneRecord;
    private TelephoneInterception mTelephoneInterception;
    private String mNumber;

    public TelephoneStateListener() {
        mTelephoneRecord = new TelephoneRecord();
        mTelephoneInterception = new TelephoneInterception();
    }

    @SuppressLint("CheckResult")
    public void onCallStateChanged(final String state, String incomingNumber) {
        Log.d(TAG, "onCallStateChanged: 监听方法");
        Log.d(TAG, "onCallStateChanged: number:"+incomingNumber);
        Log.d(TAG, "onCallStateChanged: state:"+state);
        Log.d(TAG, "onCallStateChanged: 对比：" + state.equals(TelephonyManager.EXTRA_STATE_RINGING));
        if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
            Log.d(TAG, "onCallStateChanged: 对比2：state.equals(TelephonyManager.EXTRA_STATE_RINGING)");
            mNumber = incomingNumber;
        }
        Log.d(TAG, "onCallStateChanged: mNumber:"+mNumber);
        Completable.create(new CompletableOnSubscribe() {
            @Override
            public void subscribe(CompletableEmitter emitter) throws Exception {
                Log.d(TAG, "subscribe: Rxjava teread"+state);
                if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
                    Log.d(TAG, "onCallStateChanged: OFFHOOK");
                    mTelephoneRecord.telephoneRecord(mNumber);
                } else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
                    Log.d(TAG, "onCallStateChanged: IDLE");
                    mTelephoneRecord.stopTelephoneRecord();
                } else if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
                    Log.d(TAG, "onCallStateChanged: RINGING");

                    mTelephoneInterception.telephoneInterception(mNumber);
                }
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.io()).subscribe();

    }

}
